import { CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { Request } from 'express';
import { Observable } from 'rxjs';

@Injectable()
export class LoginGuard implements CanActivate {

  @Inject(JwtService)
  private jwt:JwtService;

  canActivate(
    context: ExecutionContext,
  ): boolean | Promise<boolean> | Observable<boolean> {
    
    const request : Request = context.switchToHttp().getRequest();
    const authorization = request.header('authorization');
    const bearer = authorization.split(' ');

    console.log(bearer);

    if(!bearer || bearer.length < 2){
      throw new UnauthorizedException('Login token error, please try again...');
    }


    const token = bearer[1];

    try{ 
      const info = this.jwt.verify(token);
      (request as any).user = info.user;
      return true;
    }catch(e){
      throw new UnauthorizedException('Login token error, please try again...'); 
    }

  }

}